package org.gradle.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
@ComponentScan("org.gradle")
//@MapperScan("org.gradle.mapper.mapper")
public class BootConfig {

    @Bean
    public DataSource dataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8");
            dataSource.setUser("root");
            dataSource.setPassword("");
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        Resource[] mapperLocations = new Resource[1];
        Resource resource = new ClassPathResource("mapping/UsersMapper.xml");
        mapperLocations[0] = resource;

        factoryBean.setMapperLocations(mapperLocations);
        factoryBean.setDataSource(dataSource);
        return factoryBean;
    }

    @Bean
    public SqlSession sqlSession(SqlSessionFactory sqlSessionFactoryBean){
        SqlSession sqlSession = new SqlSessionTemplate(sqlSessionFactoryBean);
        return sqlSession;
    }

    //@MapperScan 采用的是 org.mybatis.spring.mapper.MapperScannerConfigurer
    //而 这里需要  tk.mybatis.spring.mapper.MapperScannerConfigurer
    // 最新的 tk.mybatis 已经支持 MapperScan。而不再是 spring-boot的专利
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("org.gradle.mapper.mapper");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return mapperScannerConfigurer;
    }
}
